package com.CMS.server;

import java.util.Date;
import java.util.List;

import com.CMS.client.PageService;
import com.CMS.server.dao.ItemMenuDao;
import com.CMS.server.dao.LanguageDao;
import com.CMS.server.dao.PageDao;
import com.CMS.server.dao.UserDao;
import com.CMS.server.domain.ItemMenu;
import com.CMS.server.domain.Language;
import com.CMS.server.domain.Page;
import com.CMS.server.domain.PageVersion;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RpcPage extends RemoteServiceServlet implements PageService{

	/**
	 * 
	 */
	private static final long serialVersionUID = -7883031600335776096L;

	@Override
	public void create(Page page) {
		PageDao dao = new PageDao();
		dao.createEntity(page);
	}

	@Override
	public void create(String name, String extension, long idLanguage,
			long idItemMenu, String content,boolean activa, String alias) {
		
		LanguageDao daoLang = new LanguageDao();
		Language lang = daoLang.getEntity(idLanguage);
		
		ItemMenuDao daoItem = new ItemMenuDao();
		ItemMenu item = daoItem.getEntity(idItemMenu);
		
		PageVersion version = new PageVersion();
		version.setContent(content);
		version.setFlagActiva(activa);
		version.setNroVersion(1);
		UserDao daoUser = new UserDao();
		version.setUser(daoUser.getUserByAlias(alias));
		
		Page p = new Page();
		p.setName(name+"."+extension);
		p.setDescription(name);
		p.setExtension(extension);
		p.setLang(lang);
		p.setVersiones(version);
		p.setItem(item);
		
		PageDao dao = new PageDao();
		dao.createEntity(p);
	}

	@Override
	public List<Page> fetch() {
		PageDao dao = new PageDao();
		return dao.getAll();
	}

	@Override
	public List<Page> getVisiblePages() {
		PageDao dao = new PageDao();
		return dao.getAll();
	}

	@Override
	public Page getPage(long id) {
		PageDao dao = new PageDao();
		return dao.getEntity(id);
	}

	@Override
	public void update(long id, String name, String extension, long idLanguage,
			long idItemMenu, String content, boolean activa, String alias) {
		PageDao dao = new PageDao();
		Page p = dao.getEntity(id);
		LanguageDao lDao = new LanguageDao();
		Language l = lDao.getEntity(idLanguage);
		ItemMenuDao iDao = new ItemMenuDao();
		ItemMenu i = iDao.getEntity(idItemMenu);
		p.setLang(l);
		p.setItem(i);
		p.setName(name);
		p.setExtension(extension);
		p.setModDate(new Date());
		
		PageVersion version = new PageVersion();
		version.setContent(content);
		version.setFlagActiva(activa);
		version.setNroVersion(p.getLastVersion().getNroVersion() + 1);
		UserDao uDao = new UserDao();
		version.setUser(uDao.getUserByAlias(alias));
		p.setVersiones(version);
		
		dao.updateEntity(p);
	}

}
